<template>
  <div class="posts">
    <a-form layout="inline" :model="searchForm" autocomplete="off">
      <a-form-item label="标题：">
        <a-input allowClear v-model:value="searchForm.title"></a-input>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="search">查询</a-button>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="add">新增文章</a-button>
      </a-form-item>
    </a-form>
    <a-table
      :columns="columns"
      :data-source="tableData"
      :pagination="{ current: searchForm.pageNum, pageSize: searchForm.pageSize, total: searchForm.total, onChange: currentChange, showTotal: total => `总数：${searchForm.total}` }"
      :loading="searchForm.loading"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'index'">
          <span>{{ index + 1 }}</span>
        </template>
        <template v-else-if="column.key === 'tags'">
          <span>
            <a-tag
              v-for="tag in record.tags"
              :key="tag"
              :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
            >{{ tag.toUpperCase() }}</a-tag>
          </span>
        </template>
        <template v-else-if="column.key === 'operation'">
          <span>
            <a @click="view(record)">查看</a>
            <a-divider type="vertical" />
            <a @click="edit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="deletePost(record)">删除</a>
          </span>
        </template>
      </template>
    </a-table>

    <a-modal
      :title="formDialog.title"
      width="600px"
      v-model:visible="formDialog.show"
      :onCancel="closeFormDialog"
      @ok="submit"
    >
      <a-form :label-col="{ span: 4 }" :model="form" ref="formRef">
        <a-form-item label="作者：" name="author">
          <a-input v-model:value="form.author" autocomplete="off"></a-input>
        </a-form-item>
        <a-form-item label="标题：" name="title">
          <a-input v-model:value="form.title" autocomplete="off"></a-input>
        </a-form-item>
        <a-form-item label="内容：" name="content">
          <a-input v-model:value="form.content" type="textarea" autocomplete="off"></a-input>
        </a-form-item>
        <a-form-item label="地址：" name="thumb_url">
          <a-input v-model:value="form.thumb_url" type="textarea" autocomplete="off"></a-input>
        </a-form-item>
        <a-form-item label="图标名称：" name="icon">
          <a-input v-model:value="form.icon" type="textarea" autocomplete="off"></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { getPostsApi, deletePostApi, updatePostApi, createPostApi } from './service';
import { FormInstance, message, Modal } from 'ant-design-vue';

// interface FormState {
//   username: string;
//   password: string;
//   remember: boolean;
// }
const formRef = ref<FormInstance>()

onMounted(() => {
  init()
})

const tableData = ref<[]>([])
const columns = ref<any>(
  [
    {
      title: "序号",
      key: 'index'
    },
    {
      title: "标题",
      dataIndex: "title",
    },
    {
      title: "作者",
      dataIndex: "author",
    },
    {
      title: "内容",
      dataIndex: "content",
    },
    {
      title: "地址",
      dataIndex: "thumb_url",
    },
    {
      title: "图标名称",
      dataIndex: "icon",
    },
    {
      title: "类型",
      dataIndex: "type",
    },
    {
      title: "创建事件",
      dataIndex: "create_time",
    },
    {
      title: "更新时间",
      dataIndex: "update_time",
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 200
    },
  ]

)
const searchForm = reactive<any>(
  {
    title: '',
    pageNum: 1,
    pageSize: 10,
    total: 0,
    loading: false,
  }
)

const formDialog = reactive<any>({
  show: false,
  type: 'add',
  title: '',
});
const form = reactive<any>({
  id: null,
  title: '',
  author: '',
  content: '',
  thumb_url: 'http://',
  type: 0,
  icon: ''
});

const init = () => {
  search();
}

const resetForm = () => {
  formRef?.value?.resetFields();
}
const search = () => {
  searchForm.pageNum = 1;
  getPosts();
}
const view = (row) => {
  formDialog.type = 'view';
}
const currentChange = (pageNum) => {
  searchForm.pageNum = pageNum;
  getPosts();
}
const deletePost = async (record) => {
  Modal.confirm({
    title: '提示',
    content: '确定要删除吗?',
    async onOk() {
      await deletePostApi({ id: record.id })
      message.success('删除成功');
      getPosts();
    },
    onCancel() { },
  });


}
const add = () => {
  formDialog.type = 'add';
  formDialog.title = '新增';
  formDialog.show = true;
}
const edit = (row) => {
  formDialog.type = 'edit';
  formDialog.title = '编辑';
  formDialog.show = true;
  setFormData(row);
}
const setFormData = (item) => {
  nextTick(() => {
    form.id = item.id || null;
    form.title = item.title;
    form.author = item.author;
    form.content = item.content;
    form.type = item.type;
    form.thumb_url = item.thumb_url;
    form.icon = item.icon;
  });
}
const closeFormDialog = () => {
  form.id = null;
  resetForm();
}
const getPosts = async () => {
  const params = {
    pageNum: searchForm.pageNum,
    pageSize: searchForm.pageSize,
    title: searchForm.title,
  };
  searchForm.loading = true;
  const res = await getPostsApi(params)
  searchForm.loading = false;
  tableData.value = res.list || [];
  searchForm.total = res.total || 0;
}

const createPost = async () => {
  try {
    await createPostApi(form);
    message.success('新增文章成功');
    formDialog.show = false;
    getPosts();
  } catch (error: any) {
    // message.error(error.msg);
  }
}
const updatePost = async () => {
  try {
    await updatePostApi(form)
    message.success('更新文章成功');
    formDialog.show = false;
    getPosts();
  } catch (error) {

  }
}
const submit = () => {
  if (formDialog.type === 'add') {
    createPost();
  } else {
    updatePost();
  }
}

</script>

<style lang="less">
</style>
